/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkRtspAuthenticator.h"
#include "MkUtil/MkMd5.h"
#include "MkUtil/MkBase64.h"
#include "MkUtil/MkLog.h"
CMkRtspAuthenticator::CMkRtspAuthenticator()
    :m_bMd5Pass(FALSE)
    , m_bBasic(FALSE)
{

}

Uint32 CMkRtspAuthenticator::GetDigestResponse(const MkString& Method, const MkString& Uri, MkString& Response)
{
    if (m_bMd5Pass) {
        Response = CMkMd5Encode::Encode(m_Password + ":" + m_Nonce + ":" + CMkMd5Encode::Encode(Method + ":" + Uri));
    } else {
        MkString s1 = CMkMd5Encode::Encode(m_UserName + ":" + m_Realm + ":" + m_Password);
        MkString s2 = CMkMd5Encode::Encode(Method + ":" + Uri);
        MkString s3 = CMkMd5Encode::Encode(s1 + ":" + m_Nonce + ":" + s2);
        Response = CMkMd5Encode::Encode(CMkMd5Encode::Encode(m_UserName + ":" + m_Realm + ":" + m_Password) + ":" + m_Nonce + ":" + CMkMd5Encode::Encode(Method + ":" + Uri));
    }
    return NoneError;
}

Uint32 CMkRtspAuthenticator::GetDigestRequest(MkString& WWWAuthenticate)
{
    WWWAuthenticate = "Digest realm=\"" + m_Realm + "\", nonce=\"" + m_Nonce + "\", stale=\"FALSE\"";
    return NoneError;
}

Uint32 CMkRtspAuthenticator::GetBasicResponse(MkString& Response)
{
    MkString BaseAuthor;
    Uint32 ErrorCode = MkBase64Encode(m_UserName + ":" + m_Password, BaseAuthor);
    MkCheckErrorLog(ErrorCode, "basic 64 encode failed\n");
    Response = "Basic " + BaseAuthor;
    return NoneError;
}

Uint32 CMkRtspAuthenticator::GetBasicRequest(MkString& WWWAuthenticate)
{
    WWWAuthenticate = "Basic realm=\"" + m_Realm + "\"";
    return NoneError;
}

BOOL CMkRtspAuthenticator::operator==(const CMkRtspAuthenticator& Other)
{
    return m_Password == Other.GetPassword()
        && m_UserName == Other.GetUserName()
        && m_Realm == Other.GetRealm()
        && m_Nonce == Other.GetNonce()
        && m_bMd5Pass == Other.GetIsMd5Pass();
}

CMkRtspAuthenticator::~CMkRtspAuthenticator()
{

}